package com.wkk.service.impl;

import com.wkk.entity.*;
import com.wkk.mapper.AdminMapper;
import com.wkk.mapper.CoachMapper;
import com.wkk.mapper.UserMapper;
import com.wkk.service.UserService;
import com.wkk.util.GeneralCalculation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private CoachMapper coachMapper;

    @Override
    public User userLogin(User user) {
        User nowUser = userMapper.selectOneByNameAndPwd(user);
        if(nowUser == null){
            nowUser = userMapper.selectOneByMobileAndPwd(user);
        }
        if(nowUser.getLevel().equals("coach")){
            Coach coach = coachMapper.selectOneByMobile(nowUser.getMobile());
            if(coach==null){
                coach = new Coach();
                coach.setCid(0);
            }
            nowUser.setCoach(coach);
        }
        return nowUser;
    }

    @Override
    public String userRegister(User user) {
        List<User> userList = userMapper.selectList();
        String info = "1";
        for(User one : userList){
            if(one.getUsername().equals(user.getUsername())){
                    info = "该用户名已经被注册！";
                    return info;
            }
            if(one.getMobile().equals(user.getMobile())){
                    info = "该手机号已被注册！";
                   return info;
            }
        }
        //若是添加会员则传递的cid存在值
        //如果是会员则调用底层插入会员sql
        if(user.getCid()!=null){
            GeneralCalculation generalCalculation = new GeneralCalculation();
            user.setEndMember(generalCalculation.getMemberTime(user.getCid()));
            userMapper.insertMember(user);
            return info;
        }

        user.setCreateTime(new Timestamp(new Date().getTime()).toString());
        user.setLevel("user");
        userMapper.insertOne(user);
        return info;
    }

    @Override
    public void updateToUser(Integer uid) {
        userMapper.updateToUser(uid);
    }


    @Override
    public User selectOne(Integer uid) {
        return userMapper.selectOne(uid);
    }

    @Override
    public String userInfoUpdate(User user) {
        List<User> userList = userMapper.selectList();
        userList.remove(userMapper.selectOne(user.getUid()));
        for(User one : userList){
            if(one.getMobile().equals(user.getMobile())){
                return "该手机号已被其他用户注册";
            }
        }
        userMapper.updateUserInfo(user);
        return "成功";
    }

    @Override
    public boolean userChangePassword(String mobile) {
        int i = 0;
        i = userMapper.updatePassword(mobile);
        return i == 1?true:false;
    }

    @Override
    public boolean userChangePassword(User user) {
        int i = 0;
        i = userMapper.updatePasswordByUid(user);
        return i == 1?true:false;
    }

    @Override
    public PageBean<User> selectPageByCondition(Integer current, String condition) {
        Map<String,Object> map = new HashMap<>();
        PageBean<User> pageBean = new PageBean<>();
        pageBean.setCurrent(current);
        map.put("condition",condition);
        int pageSize = 10;//每页用户数
        pageBean.setSize(pageSize);
        int total = userMapper.selectListByCondition(condition).size();//满足条件的总用户数
        pageBean.setTotal(total);
        double tc = total;
        Double pages = Math.ceil(tc/pageSize);//向上取整
        pageBean.setPages(pages.intValue());//总页数
        map.put("start",(current-1)*pageSize);//分页查询的起始点
        map.put("size",pageBean.getSize());//分页查询的用户长度
        pageBean.setRecords(userMapper.selectListByConditionLimit(map));
        return pageBean;
    }

    @Override
    public PageBean<User> queryPageByUserInfo(User user) {
        //精确查询不做分页，但是用一页信息封装，为了前端读取方便，不用再多写JS代码
        PageBean<User> pageBean = new PageBean<>();
        int pageSize = 100;//每页用户数
        pageBean.setCurrent(1);
        pageBean.setSize(pageSize);
        List<User> userList = userMapper.exactQueryList(user);
        int total = userList.size();//满足条件的总用户数
        pageBean.setTotal(total);
        double tc = total;
        Double pages = Math.ceil(tc/pageSize);//向上取整
        pageBean.setPages(pages.intValue());//总页数
        pageBean.setRecords(userList);
        return pageBean;
    }

    @Override
    public boolean deleteUserByUid(Integer uid) {
        int i = 0;
        i = userMapper.deleteUser(uid);
        return i==1?true:false;
    }

    @Override
    public boolean upToMember(Integer uid,Integer cid,String myself) {
       // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Card card = adminMapper.selectCardByCid(cid);
        User user = new User();
        Income income = new Income();
        user.setUid(uid);
        GeneralCalculation generalCalculation = new GeneralCalculation();
 /*       int days = 0;
        if(card.getTitle()==1){
            days = 31;//月卡
        }
        if(card.getTitle()==2){
            days = 124;//学期卡
        }
        if(card.getTitle()==3){
            days = 186;//半年卡
        }
        if(card.getTitle()==4){
            days = 365;//年卡
        }
        if(card.getTitle()==5){
            days = 730;//两年卡
        }
        if(card.getTitle()==6){
            days = 100000;//永久卡
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.DATE,days);
        Date date = calendar.getTime();*/
        user.setEndMember(generalCalculation.getMemberTime(card.getTitle()));
        user.setMyself(myself);
        userMapper.updateUserLevel(user);
        int i = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        income.setDate(simpleDateFormat.format(Calendar.getInstance().getTime()));
        income.setType("会员卡收入");
        income.setMoney(card.getPrice());
        adminMapper.insertOneIncome(income);

        return i==1?true:false;
    }

    @Override
    public List<User> selectList() {
        return userMapper.selectList();
    }

    @Override
    public User updateByMember(User user) {
        userMapper.updateUserByMember(user);
        return userMapper.selectOne(user.getUid());
    }

    @Override
    public List<User> selectListByCid(Integer cid) {
        return userMapper.selectListByCid(cid);
    }

    @Override
    public User selectOneByMobile(String mobile) {
        return userMapper.selectOneByMobile(mobile);
    }

    @Override
    public boolean updateUserCid(User user) {
        int i = 0;
        i = userMapper.updateUserCid(user);
        return i==1?true:false;
    }

    @Override
    public boolean updateUserCidState(Integer uid) {
        int i = 0;
        i = userMapper.updateUserCidState(uid);
        //在用户确认连接之后 进行判断
        Calendar calendar = Calendar.getInstance();
        Integer nowMonth = calendar.get(Calendar.MONTH) + 1;//获取当前月份
        Integer nowYear = calendar.get(Calendar.YEAR);//获取当前年份
        //1.找到该教练信息
        Coach coach = coachMapper.selectOneByCid(userMapper.selectOne(uid).getCid());
        //2.查找该用户在本月之内是否已经连接过,即二次连接不算总数
        //3.如果通过第一步则改变该教练的业绩表,并找到该月业绩进行学员添加
        CoachConnectMember coachConnectMember = new CoachConnectMember(coach.getCid(),uid,nowYear,nowMonth);
        CoachConnectMember list = coachMapper.selectCCMByCid(coachConnectMember);
        if(list==null){
            coachMapper.insertIntoCCM(coachConnectMember);//插入数据
            CoachPerformance nowPerformance = new CoachPerformance(coach.getCid(),nowMonth,nowYear);
            CoachPerformance coachPerformance = coachMapper.selectOneP(nowPerformance);
            if(coachPerformance==null){//如果当年当月的该教练业绩不存在，则先添加此业绩,再进行更新学员个数
                coachMapper.insertPerformance(nowPerformance);
                CoachPerformance coachPerformance1 = coachMapper.selectOneP(nowPerformance);
                coachMapper.updatePStudentCount(coachPerformance1);
            }else{
                coachMapper.updatePStudentCount(coachPerformance);//连接成功后更新本月教练的学员个数
            }
        }
        return i==1?true:false;
    }

    @Override
    public boolean stopConnectByCoach(Integer uid) {
        int i = 0;
        i = userMapper.updateUserCidAndState(uid);
        return i==1?true:false;
    }


}
